<?php

namespace app\admin\model\groupon\order;

use think\Model;

class OrderStoreExpress extends Model
{
    // 表名
    protected $name = 'groupon_order_store_express';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 发货状态
    const DISPATCH_STATUS_NOSEND = 0;       // 未发货
    const DISPATCH_STATUS_SENDED = 1;        // 已发货
    const DISPATCH_STATUS_GETED = 2;        // 已收货

    // 追加属性
    protected $append = [
        'dispatch_status_text'
    ];


    public static function getCode($user_id)
    {
        $rand = $user_id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999);
        $order_sn = date('Yhis') . $rand;

        $id = str_pad($user_id, (24 - strlen($order_sn)), '0', STR_PAD_BOTH);

        return 'S' . $order_sn . $id;
    }

    public function getDispatchStatusList()
    {
        return ['0' => '未发货', '1' => '已发货', '2' => '已收货'];
    }

    public function getDispatchStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['dispatch_status']) ? $data['dispatch_status'] : '');
        $list = $this->getDispatchStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 记得用的时候一定要额外加上 order_id 等于当前订单号
     */
    public function item()
    {
        return $this->hasMany(\app\admin\model\groupon\order\OrderItem::class, 'store_express_id');
    }

    public function store()
    {
        return $this->belongsTo(\app\admin\model\groupon\store\Store::class, 'store_id');
    }


    public function log()
    {
        return $this->hasMany(\app\admin\model\groupon\order\OrderExpressLog::class, 'order_express_id')->order('id', 'desc');
    }
}
